import { Injectable } from '@nestjs/common';
import { OrderDto, OrderEditDto, TokenInfo } from './order.dto'
import * as db from '../../../entity'
// import { Between } from 'typeorm';
import * as dateFns from 'date-fns'
import { serverCode } from '../../../tool/server.code'


// async function checkToken(token: string) {
//     const findToken = await db.UserToken.findOne({
//         where: {
//             token: token,
//             status: db.UserTokenStatusEnum.ENABLE,
//             type: db.UserTokenTypeEnum.USER,
//         }
//     })
//     if (!findToken) {
//         return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
//     }
//     if (dateFns.isAfter(new Date(), findToken.expire_time)) {
//         findToken.status = db.SmsCodeStatusEnum.DISABLE;
//         findToken.save();
//         return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
//     }
//     findToken.expire_time = dateFns.addDays(new Date(), 3);
//     await findToken.save();
//     const user = await db.UserAccount.findOne({
//         where: {
//             user_id: findToken.user_id
//         }
//     })
//     return user;
// }

@Injectable()
export class OrderService {
    // constructor(private readonly) { }

    async add(orderInfo: OrderDto) {
        const findToken = await db.UserToken.findOne({
            where: {
                token: orderInfo.token,
                status: db.UserTokenStatusEnum.ENABLE,
                type: db.UserTokenTypeEnum.USER,
            }
        })
        if (!findToken) {
            return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
        }
        if (dateFns.isAfter(new Date(), findToken.expire_time)) {
            findToken.status = db.SmsCodeStatusEnum.DISABLE;
            findToken.save();
            return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
        }
        findToken.expire_time = dateFns.addDays(new Date(), 3);
        await findToken.save();
        const user = await db.UserAccount.findOne({
            where: {
                user_id: findToken.user_id
            }
        })
        const order = await db.Order.create({
            name: orderInfo.data.name,
            wxname: orderInfo.data.wxname,
            city: orderInfo.data.city,
            lend: orderInfo.data.lendLimitId,
            time_limit: orderInfo.data.lendTimeId,
            purpose: orderInfo.data.lendAimId,
            mobile: user.mobile,
            user_id: user.user_id
        })
        await order.save();
        return { data: { id: order.order_id } };
    }
    async edit(order: OrderEditDto) {
        const findToken = await db.UserToken.findOne({
            where: {
                token: order.token,
                status: db.UserTokenStatusEnum.ENABLE,
                type: db.UserTokenTypeEnum.USER,
            }
        })
        if (!findToken) {
            return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
        }
        if (dateFns.isAfter(new Date(), findToken.expire_time)) {
            findToken.status = db.SmsCodeStatusEnum.DISABLE;
            findToken.save();
            return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
        }
        findToken.expire_time = dateFns.addDays(new Date(), 3);
        await findToken.save();

        const orderInfo = await db.Order.findOne({
            where: {
                order_id: order.data.orderId
            }
        })
        if (!orderInfo) {
            return { code: 1, msg: '订单号未知' }
        }
        orderInfo.income = order.data.incomeId;
        orderInfo.income_type = order.data.incomeTypeId;
        orderInfo.social_insurance = order.data.sbId;
        orderInfo.accumulation_fund = order.data.gjjId;
        orderInfo.work_year = order.data.workYearId;
        orderInfo.house = order.data.houseId;
        orderInfo.car = order.data.carId;
        orderInfo.status = db.OrderStatusEnum.NORMAL;
        await orderInfo.save();
        return { data: {} };
    }

    async reApply(tokenInfo: TokenInfo) {
        const findToken = await db.UserToken.findOne({
            where: {
                token: tokenInfo.token,
                status: db.UserTokenStatusEnum.ENABLE,
                type: db.UserTokenTypeEnum.USER,
            }
        })
        if (!findToken) {
            return { msg: '访问令牌不存在', code: serverCode.LOGINAUTHFAIL }
        }
        if (dateFns.isAfter(new Date(), findToken.expire_time)) {
            findToken.status = db.SmsCodeStatusEnum.DISABLE;
            findToken.save();
            return { msg: '访问令牌已经过期，请重新获取', code: serverCode.LOGINAUTHFAIL }
        }
        findToken.expire_time = dateFns.addDays(new Date(), 3);
        await findToken.save();

        const orderInfo = await db.Order.query(`select * from \`order\` where user_id=${findToken.user_id} and status in (${db.OrderStatusEnum.NORMAL},${db.OrderStatusEnum.PAID}) order by update_time DESC limit 1`)
        // const orderInfo = await db.Order.findOne({
        //     where: {
        //         user_id: findToken.user_id,
        //         status: (db.OrderStatusEnum.NORMAL, db.OrderStatusEnum.PAID),
        //     },
        //     order: {
        //         'update_time': 'DESC'
        //     }
        // })
        if (!orderInfo.length) {
            return { data: { reApply: 1 } }
        }
        if (dateFns.isAfter(new Date(), dateFns.addDays(orderInfo[0].update_time, 3))) {
            return { data: { reApply: 1, applyTime: dateFns.format(orderInfo[0].update_time, 'YYYY-MM-DD HH:mm') } }
        }
        return { data: { reApply: 0, applyTime: dateFns.format(orderInfo[0].update_time, 'YYYY-MM-DD HH:mm') } }
    }
}